﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace T4ViewModel
{
    public abstract class ViewModel<ModelType>
        where ModelType : new()
    {
        public ViewModel() { }
        public ViewModel(ModelType model)
        {
            foreach (var property in GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                var modelProperty = typeof(ModelType).GetProperty(property.Name, BindingFlags.Instance | BindingFlags.Public);
                if (property != null && modelProperty != null)
                    property.SetValue(this, modelProperty.GetValue(model));
            }
        }

        public ModelType ToModel()
        {
            var model = new ModelType();
            ToModel(model);
            return model;
        }

        public void ToModel(ModelType model, params Expression<Func<ModelType, object>>[] excludedProperties)
        {
            var excludedNames = excludedProperties.Select(ep => ExpressionParser.GetPropertyName(ep));
            foreach (var property in GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                if (!excludedNames.Contains(property.Name))
                {
                    var modelProperty = typeof(ModelType).GetProperty(property.Name, BindingFlags.Instance | BindingFlags.Public);
                    if (modelProperty != null)
                        modelProperty.SetValue(model, property.GetValue(this));
                }
            }
        }

    }
}
